package educrypt.analysis;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class AnalysisNgrams implements Iterable<String> {
	public final static boolean OVERLAPING = true;
	public final static boolean NO_OVERLAPING = false;

	private List<String> data;

	public AnalysisNgrams() {
		this.data = new ArrayList<String>();
	}

	public AnalysisNgrams(String data, int segmentLength, boolean overlaping) {
		if (overlaping == AnalysisNgrams.OVERLAPING) {
			this.data = this.splitTextOverlaping(data, segmentLength);
		} else {
			this.data = this.splitText(data, segmentLength);
		}
	}

	public void addNgram(String ngram) {
		this.data.add(ngram);
	}

	public void removeNgram(String ngram) {
		this.data.remove(this.data.indexOf(ngram));
	}

	public int size() {
		return data.size();
	}

	public String getNgram(int pos) {
		return this.data.get(pos);
	}

	public boolean containsNgram(String ngram) {
		return this.data.contains(ngram);
	}

	@Override
	public Iterator<String> iterator() {
		return data.iterator();
	}

	private List<String> splitTextOverlaping(String data, int segmentLength) {
		// hello -> he, el, ll, lo
		return splitText(data, segmentLength, 1);
	}

	private List<String> splitText(String data, int segmentLength) {
		// hello -> he, ll, o
		return splitText(data, segmentLength, segmentLength);
	}

	private List<String> splitText(String data, int segmentLength, int increment) {
		List<String> processedData = new ArrayList<String>();

		for (int i = 0; i < data.length(); i = i + increment) {
			int endIndex = i + segmentLength;
			boolean notEnoughCharacters = endIndex >= data.length();
			if (notEnoughCharacters) {
				endIndex = data.length();
			}
			String ngram = data.substring(i, endIndex);
			if (notEnoughCharacters) {
				for (int j = ngram.length(); j < segmentLength; j++) {
					ngram = ngram + " ";
				}
			}
			processedData.add(ngram);
		}
		return processedData;
	}
}
